/*
 * HttpParser.h
 *
 *  Created on: 2018年7月3日
 *      Author: zhengboyuan
 */

#ifndef HTTPPARSER_H_
#define HTTPPARSER_H_

#include "BasicType.h"
#include <string>
#include <map>

#include "http_parser.h"


class HttpParser
{
public:
    enum Event
    {
        Parser_MessageBegin,
        Parser_Url,
        Parser_StatusComplete,
        Parser_HeaderField,
        Parser_HeaderValue,
        Parser_HeadersComplete,
        Parser_Body,
        Parser_MessageComplete,
    };

    static const uint8_t MAGIC = '$';

public:
    HttpParser(enum http_parser_type type);
    virtual ~HttpParser();

    enum http_parser_type getType() { return (http_parser_type)m_parser.type; }

    int execute(const char* buffer, size_t count);

	int onParser(Event, const char*, size_t);

	void reset();

protected:
    virtual int onMessageBegin() { return 0; }
    virtual int onUrl(const char*, size_t) { return 0; }
    virtual int onHeader(const std::string& field, const std::string& value) { return 0; }
    virtual int onHeadersComplete() { return 0; }
    virtual int onBody(const char*, size_t) { return 0; }
    virtual int onMessageComplete() { return 0; }
    virtual int onUpgrade(const char*, size_t) { return 0; }
    virtual int onError(int code) { m_errorCode = code; return 0; }

protected:

    int handleMessageBegin();
    int handleHeaderField(const char*, size_t);
    int handleHeaderValue(const char*, size_t);
    int handleHeadersComplete();


protected:
    struct http_parser m_parser;
    http_parser_type    m_type;

    std::string m_curField;
    std::string m_curValue;
    bool m_lastWasValue;

    int m_errorCode;


};

#endif /* HTTPPARSER_H_ */
